//
//  Common.m
//  WisdomZhuHai
//
//  Created by yewei on 13-9-18.
//  Copyright (c) 2013年 wyd. All rights reserved.
//

#import "Common.h"
#import "ProtocolManager.h"
#include "sys/types.h"
#include "sys/sysctl.h"
#include <net/if.h>
#include <net/if_dl.h>
#include <mach-o/dyld.h>

typedef void (^AutoDismissAlertViewBlock)();

@interface Common()

@property (nonatomic,retain) UIView *callView;
@property (nonatomic,strong) UIAlertView *autoDismissAlertView;
@property (nonatomic,copy) AutoDismissAlertViewBlock autoDismissAlertViewBlock;

-(void)callWithPhoneNumber:(NSString *)str;

@end

@implementation Common

@synthesize callView;
@synthesize adjustCoordinateForGoogle;

Common *sharedCommon= nil;

+ (Common*)shareInstance
{
    if (sharedCommon == nil)
    {
        sharedCommon = [[Common alloc] init];
    }
    return sharedCommon;
}

- (id)init
{
    self = [super init];
    if (self) {
        self.callView = nil;
        adjustCoordinateForGoogle = CLLocationCoordinate2DMake(0.005772000000000332,0.006506999999999152);
    }
    
    return self;
}

-(void)dealloc
{
    [callView release];
    [super dealloc];
}

//获取${xxx}格式的xxx
+(NSString *)getValueByFormatString:(NSString *)str
{
    if([str hasPrefix:@"${"])
    {
        NSString *result = [str substringFromIndex:2];
        return [result substringToIndex:([result length]-1)];
    }
    return @"";
}

+ (NSDictionary*)getUserAccountInfo:(NSString *)str
{
    return nil;
}

-(BOOL)isRetinaMode
{
    int scale = [UIScreen mainScreen].scale;
    BOOL bRetinaMode  = scale == 2 ? YES:NO;
    return bRetinaMode;
}

+ (BOOL)checkNetReachable
{
    NSLog(@"%s || curNetworkStatus = %d",__FUNCTION__, ((AppDelegate *)[UIApplication sharedApplication].delegate).curNetworkStatus);
    if (((AppDelegate *)[UIApplication sharedApplication].delegate).curNetworkStatus == NotReachable)
    {
        return NO;
    }
    return YES;
}
-(NSString *)getDate
{
    NSDate *  senddate=[NSDate date];
    NSDateFormatter  *dateformatter=[[NSDateFormatter alloc] init];    
    [dateformatter setDateFormat:@"YYYY-MM-dd"];
    NSString *  locationString=[dateformatter stringFromDate:senddate];    
    NSLog(@"locationString:%@",locationString);    
    [dateformatter release];
    return locationString;
}

-(NSString *)getTimeOfToday
{
    NSDate *  senddate=[NSDate date];
    NSDateFormatter  *dateformatter=[[NSDateFormatter alloc] init];
    [dateformatter setDateFormat:@"HH:mm:ss"];
    NSString *  locationString=[dateformatter stringFromDate:senddate];
    [dateformatter release];
    return locationString;
}

-(CLLocationCoordinate2D)AdjustLocationCoordinateForGoogle:(CLLocationCoordinate2D)coor
{
    return CLLocationCoordinate2DMake(coor.latitude+adjustCoordinateForGoogle.latitude, coor.longitude+adjustCoordinateForGoogle.longitude);
}

- (void)performDismissAlertView:(NSTimer *)timer
{
    [self.autoDismissAlertView dismissWithClickedButtonIndex:0 animated:YES];
}

//自动消失的alertView
-(void)showAlertViewWithTitle:(NSString *)title text:(NSString *)text dismissTime:(float)second
{
    if (self.autoDismissAlertView != nil)
    {
        return;
    }
    
    self.autoDismissAlertView = [[[UIAlertView alloc] initWithTitle:title message:text delegate:self cancelButtonTitle:nil otherButtonTitles:nil, nil] autorelease];
    
    [NSTimer scheduledTimerWithTimeInterval:second target:self selector:@selector(performDismissAlertView:) userInfo:nil repeats:NO];
    [self.autoDismissAlertView show];
    
}

- (void)showAlertViewWithTitle:(NSString *)title text:(NSString *)text dismissTime:(float)second dismissed:(void(^)())block
{
    if (self.autoDismissAlertView != nil)
    {
        return;
    }
    
    self.autoDismissAlertView = [[[UIAlertView alloc]initWithTitle:title message:text delegate:self cancelButtonTitle:nil otherButtonTitles:nil, nil] autorelease];
    self.autoDismissAlertViewBlock = block;
    
    [NSTimer scheduledTimerWithTimeInterval:second target:self selector:@selector(performDismissAlertView:) userInfo:nil repeats:NO];
    [self.autoDismissAlertView show];
}

-(void)callWithPhoneNumber:(NSString *)str
{
    NSLog(@"Call %@", str);
    UIWebView*callWebview =[[UIWebView alloc] init];
    NSURL *telURL =[NSURL URLWithString:[NSString stringWithFormat:@"tel:%@",str]];
    [callWebview loadRequest:[NSURLRequest requestWithURL:telURL]];
    //记得添加到view上
    if(self.callView != nil)
    {
        [self.callView addSubview:callWebview];
    }
    [callWebview release];
}

//根据传入的字符串，筛选出电话好吗，并提供拨号功能
-(void)callWithPhoneString:(NSString *)phoneString inView:(UIView *)view
{
    self.callView = view;
    NSLog(@"onCall");
    NSError *error;
    NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"\\d{10,16}|\\d{2,5}-\\d{3,9}-\\d{1,5}|\\d{7,9}-\\d{1,4}|(\\d{3,6}-)?\\d{3,9}" options:0 error:&error];
    NSMutableArray *phoneNumbers = [NSMutableArray array];
    if (regex != nil) {
        NSArray *matchArray = [regex matchesInString:phoneString options:0 range:NSMakeRange(0, [phoneString length])];
        
        for (NSTextCheckingResult* res in matchArray) {
            NSRange resRange = [res rangeAtIndex:0];
            [phoneNumbers addObject:[phoneString substringWithRange:resRange]];
        }
    }
    if (phoneNumbers.count == 1) {
        [self callWithPhoneNumber:phoneNumbers[0]];
    }
    else if (phoneNumbers.count > 1) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:NSLocalizedString(@"SelectPhoneNumber", nil) delegate:self cancelButtonTitle:NSLocalizedString(@"Cancel", nil) otherButtonTitles:nil];
        alert.tag = 1000;
        for (NSString* str in phoneNumbers) {
            [alert addButtonWithTitle:str];
        }
        [alert show];
        [alert release];
    }

}

#pragma mark - alertView delegate
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (alertView.tag == 1000) {
        if (buttonIndex > 0) {
            [self callWithPhoneNumber:[alertView buttonTitleAtIndex:buttonIndex]];
        }
    }
}

- (void)willPresentAlertView:(UIAlertView *)alertView
{
    if ([alertView isEqual:self.autoDismissAlertView]) {
        if ([Common getIosVersion] >= 7.0) {
            return;
        }
        CGRect frame = alertView.frame;
        CGSize titleSize = [Common textSizeWithFont:[UIFont systemFontOfSize:18] constrainedToSize:CGSizeMake(frame.size.width-32, MAXFLOAT) string:alertView.title];
        CGSize msgSize = [Common textSizeWithFont:[UIFont systemFontOfSize:16] constrainedToSize:CGSizeMake(frame.size.width-32, MAXFLOAT) string:alertView.message];
        CGFloat additional = 42;
        if (titleSize.height > 0 && msgSize.height > 0) {
            additional += 8;
        }
        frame.size.height = titleSize.height + msgSize.height + additional;
        alertView.frame = frame;
    }
}

- (void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex
{
    if (alertView == self.autoDismissAlertView) {
        self.autoDismissAlertView = nil;
        if (self.autoDismissAlertViewBlock) {
            self.autoDismissAlertViewBlock();
            self.autoDismissAlertViewBlock = nil;
        }
    }
}

+ (CLLocationCoordinate2D)getCoordinateFromString:(NSString*)str
{
    if ([str isEqualToString:@""]) {
        return INVALIDCOORDINATE;
    }
    else {
        NSArray *array = [str componentsSeparatedByString:@","];
        CLLocationCoordinate2D coor;
        coor.latitude = [array[1] floatValue];
        coor.longitude = [array[0] floatValue];
        return coor;
    }
}


+ (NSURL*)getUrlByString:(NSString*)url
{
    return [NSURL URLWithString:[url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
}

+ (BOOL)regexWithType:(int)type string:(NSString *)str
{
    if([str length] == 0)
    {
        return YES;
    }
    NSString* regex = @"";
    switch (type)
    {
        case e_email:
        {
            regex = @"^[a-zA-Z0-9_-]+\\.?[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\\.[a-zA-Z0-9_-]+)+$";
        }
            break;
        case e_url:
        {
            regex = @"^[a-zA-Z0-9_-]+\\.?[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\\.[a-zA-Z0-9_-]+)+$";
        }
            break;
        case e_number:
        {
            regex = @"0|[1-9][0-9]*";
        }
            break;
        case e_phoneNumber:
        {
            regex = @"\\d{11}";
        }
            break;
        default:
            break;
    }
    NSPredicate* pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",regex];
    return [pred evaluateWithObject:str];
}

+ (UIColor*)colorWithRGB:(unsigned int)RGBValue
{
    return [UIColor colorWithRed:((RGBValue&0xFF0000)>>16)/255.0 green:((RGBValue&0xFF00)>>8)/255.0 blue:(RGBValue&0xFF)/255.0 alpha:1];
}

+ (UIColor*)colorWithRGB:(unsigned int)RGBValue alpha:(CGFloat)alpha
{
    return [UIColor colorWithRed:((RGBValue&0xFF0000)>>16)/255.0 green:((RGBValue&0xFF00)>>8)/255.0 blue:(RGBValue&0xFF)/255.0 alpha:alpha];
}

+ (UIImage*)imageWithColor:(UIColor*)color
{
    CGRect rect = CGRectMake(0.0f, 0.0f, 1.0f, 1.0f);
    UIGraphicsBeginImageContext(rect.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    
    CGContextSetFillColorWithColor(context, [color CGColor]);
    CGContextFillRect(context, rect);
    
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    return image;
}

+(CGFloat)getIosVersion
{
    return [[UIDevice currentDevice].systemVersion floatValue];
}

+ (UIImage*)getPlaceholderImage:(PlaceholderImgType)type
{
//    switch (type) {
//        case ePIT_StoreType:
//            return nil;
//        case ePIT_StoreLogo:
//            return [UIImage imageNamed:DEFAULT_ICON_140];
//        case ePIT_StorePhoto:
//            return [UIImage imageNamed:DEFAULT_IMAGE_640];
//        case ePIT_Strategy:
//            return [UIImage imageNamed:DEFAULT_ICON_240];
//        default:
//            return [UIImage imageNamed:DEFAULT_ICON_160];
//    }
    return nil;
}

+ (NSURL *)getFullDownloadPathByRelativePath:(NSString *)relativePath
{
    if(relativePath == nil){
        return nil;
    }
    if (![relativePath isKindOfClass:[NSString class]]) {
        return nil;
    }
    if ([relativePath hasPrefix:@"http://"])
    {
        return [NSURL URLWithString:relativePath];
    }
    if(relativePath.length == 0)
    {
        return nil;
    }
    NSString *path = [NSString stringWithFormat:@"%@/%@",[ProtocolManager shareInstance].api_base_img_url, relativePath];
    return [Common getUrlByString:path];
}

#define CHECKNSNULL(x) ((x==[NSNull null])?nil:x)
+(id)valueForKey:(NSString *)key dic:(NSDictionary *)dic
{
    if (key.length == 0 || [dic count] == 0)
    {
        return nil;
    }
    id object = [dic objectForKey:key];
    object = CHECKNSNULL(object);
    
    if (object == nil) {
        object = CHECKNSNULL([dic objectForKey:[key lowercaseString]]);//若key在字典中无对应值，则将key转换为小写重新查找,仍无对应值则返回nil
        return (object==nil)?CHECKNSNULL([dic objectForKey:[key uppercaseString]]):object;//将key转化为大写，其余同上
    }
    return object;
}

+(CGSize)textSizeWithFont:(UIFont *)font constrainedToSize:(CGSize)size string:(NSString *)str
{
    CGSize textSize = CGSizeZero;
    if([[UIDevice currentDevice].systemVersion floatValue] < 7.0)
    {
        textSize = [str sizeWithFont:font constrainedToSize:size lineBreakMode:NSLineBreakByWordWrapping];
    }
    else
    {
        textSize = [str boundingRectWithSize:size options:NSStringDrawingTruncatesLastVisibleLine | NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading attributes:@{NSFontAttributeName: font} context:nil].size;
    }
    return textSize;
}

-(void)showLoadingViewWithMessage:(NSString *)message
{
    UIView *window = [UIApplication sharedApplication].keyWindow;
    [[CustomLoadingView shareInstance] showLoadingViewWithSuperView:window message:message];
}
-(void)stopLoadingView
{
    [[CustomLoadingView shareInstance] stopLoadingView];
}

+(NSString *)getMacAddr
{
    //#if TARGET_IPHONE_SIMULATOR
    //    return "ff:ff:ff:ff:ff:ff";
    //#endif
    //ios7
//    if( [[UIDevice currentDevice].systemVersion floatValue] >= 7.0)
//    {
//        NSString *bundleStr=[[NSBundle mainBundle] bundleIdentifier];
//        string identifier = [bundleStr UTF8String];
//        NSString* str = [NSString stringWithUTF8String:identifier.c_str()];
//        KeychainItemWrapper* wrapper = [[KeychainItemWrapper alloc] initWithIdentifier:str accessGroup:nil];
//        NSString* uid = [wrapper objectForKey:(id)kSecAttrAccount];
//        if(uid == nil || [uid length] == 0)
//        {
//            NSUUID *pUUID=[[UIDevice currentDevice] identifierForVendor];
//            uid = [pUUID UUIDString];
//            [wrapper setObject:uid forKey:(id)kSecAttrAccount];
//        }
//        [wrapper release];
//        return [uid UTF8String];
//    }
//    
    int                 mib[6];
    size_t              len;
    char                *buf;
    unsigned char       *ptr;
    struct if_msghdr    *ifm;
    struct sockaddr_dl  *sdl;
    
    mib[0] = CTL_NET;
    mib[1] = AF_ROUTE;
    mib[2] = 0;
    mib[3] = AF_LINK;
    mib[4] = NET_RT_IFLIST;
    
    if ((mib[5] = if_nametoindex("en0")) == 0)
    {
         NSLog(@"Error: if_nametoindex error\n");
        return NULL;
    }
    
    if (sysctl(mib, 6, NULL, &len, NULL, 0) < 0)
    {
         NSLog(@"Error: sysctl, take 1\n");
        return NULL;
    }
    
    if ((buf = (char *)malloc(len)) == NULL)
    {
        NSLog(@"Could not allocate memory. error!\n");
        return NULL;
    }
    
    if (sysctl(mib, 6, buf, &len, NULL, 0) < 0)
    {
        NSLog(@"Error: sysctl, take 2");
        free(buf);
        return NULL;
    }
    
    ifm = (struct if_msghdr *)buf;
    sdl = (struct sockaddr_dl *)(ifm + 1);
    ptr = (unsigned char *)LLADDR(sdl);
    NSString *macAddress = [NSString stringWithFormat:@"%02X:%02X:%02X:%02X:%02X:%02X",
                            *ptr, *(ptr+1), *(ptr+2), *(ptr+3), *(ptr+4), *(ptr+5)];
    macAddress = [macAddress lowercaseString];
    free(buf);
    
    return macAddress;
}

//判断是否是新的版本
+(BOOL)isNewAppVersion:(NSString *)version
{
    NSDictionary* infoDict =[[NSBundle mainBundle] infoDictionary];
    NSString* localVersion =[infoDict objectForKey:@"CFBundleVersion"];
    //按点拆分版本号
    NSArray *localArray = [localVersion componentsSeparatedByString:@"."];
    NSArray *array = [version componentsSeparatedByString:@"."];
    if([array count] != 3 || [localArray count] != 3)
    {
        return NO;
    }
    int localMainNum = [[localArray objectAtIndex:0] intValue];
    int localsubNum = [[localArray objectAtIndex:1] intValue];
    int locallastNum = [[localArray objectAtIndex:2] intValue];
    int MainNum = [[array objectAtIndex:0] intValue];
    int subNum = [[array objectAtIndex:1] intValue];
    int lastNum = [[array objectAtIndex:2] intValue];
    if(MainNum > localMainNum)
    {
        return YES;
    }
    else if(MainNum == localMainNum)
    {
        if(subNum > localsubNum)
        {
            return YES;
        }
        else if(subNum == localsubNum)
        {
            if(lastNum > locallastNum)
            {
                return YES;
            }
        }
    }
    return NO;
}


@end
